<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 6/20/24
 * Time: 1:51 PM
 */

namespace App\Services;

use App\Models\WechatTitle;

class TitleService
{

    /**
     * 获取标题库列表
     *
     * @param $params
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getList($params)
    {
        $pageSize   = $params['page_size'] ?? 50;
        $title      = $params['title'] ?? '';
        $categoryId = $params['category_id'] ?? '';

        $query = WechatTitle::query();

        if ($title) {
            $query->where('title', 'like', '%' . $title . '%');
        }
        if ($categoryId) {
            $query->where('category_id', $categoryId);
        }

        $list = $query->paginate($pageSize);

        return $list;
    }


    /**
     * 获取所有标题
     *
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getAll()
    {
        return WechatTitle::query()->select('id', 'title')->get();
    }


    /**
     * 更新标题
     *
     * @param $params
     * @return bool
     */
    public function save($params)
    {
        $id         = $params['id'] ?? 0;
        $title      = $params['title'] ?? '';
        $categoryId = $params['category_id'] ?? 0;
        if (!$title) {

            return false;
        }

        if ($id) {
            $titleModel              = WechatTitle::query()->find($id);
            $titleModel->title       = $title;
            $titleModel->category_id = $categoryId;

            return $titleModel->save();
        } else {
            $titleModel              = new WechatTitle;
            $titleModel->title       = $title;
            $titleModel->category_id = $categoryId;
            $titleModel->admin_id    = request()->admin->id;

            return $titleModel->save();
        }
    }


    /**
     * 删除标题
     *
     * @param $id
     * @return bool|mixed|null
     */
    public function delete($id)
    {
        $titleModel = WechatTitle::query()->find($id);

        return $titleModel->delete();
    }
}
